package com.qm.console.utils;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.google.common.io.Files;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Component;

import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;

@Component
public class S3Util {
   private String bucket = "tarot-s3";
   private String accessKeyId = "AKIAZ2F76BMJ43DY7KET";
   private String accessKeySecret = "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";

   private String FolderName = "tarot_console/";

   private AmazonS3 amazonS3;

   @PostConstruct
   private void init() {
      ClientConfiguration config = new ClientConfiguration();
      config.setProtocol(Protocol.HTTP);
      config.disableSocketProxy();

      amazonS3 = AmazonS3ClientBuilder
              .standard()
              .withClientConfiguration(config)
              .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKeyId, accessKeySecret)))
              .withRegion(Regions.US_EAST_1) //Region配置
              .enablePathStyleAccess()
              .build();
   }

   public String uploadImage(File imageFile) {
      String extension = Files.getFileExtension(imageFile.getPath());
      String key = new Md5Hash(imageFile.getAbsolutePath()) + "." + extension;
      return uploadImage(imageFile, FolderName + key);
   }

   public String uploadImage(File imageFile, String key) {
      amazonS3.putObject(new PutObjectRequest(bucket, key, imageFile).withCannedAcl(CannedAccessControlList.PublicRead));
      GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
      amazonS3.generatePresignedUrl(urlRequest);
      return key;
   }

   public Point imageSize(File imageFile) {
      try {
         BufferedImage image = ImageIO.read(imageFile);
         return new Point(image.getWidth(), image.getHeight());
      } catch (IOException e) {
      }
      return null;
   }

   public static void main(String[] args) {
      S3Util util = new S3Util();
      util.init();
      String result = util.uploadImage(new File("D://pexels-beth-easton-2433985.jpg"));
      System.out.println(result);
   }
}
